package com.china.produce.controller;

import cn.hutool.json.JSONUtil;
import com.china.produce.message.MessageDO;
import com.china.produce.message.MessageDistributor;
import com.china.produce.message.SseEmitterMessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2025/6/24
 */
@RestController
@RequestMapping("/sse")
public class SseController {

    @Autowired
    @Qualifier("messageDistributor")
    private MessageDistributor distributor;

    @GetMapping("/connect/{sessionKey}")
    public SseEmitter connect(@PathVariable String sessionKey) {
        SseEmitter emitter = new SseEmitter(0L);
        SseEmitterMessageSender.addSession(sessionKey, emitter);
        emitter.onCompletion(() -> SseEmitterMessageSender.removeSession(sessionKey));
        emitter.onTimeout(() -> SseEmitterMessageSender.removeSession(sessionKey));
        return emitter;
    }

    @PostMapping("/send")
    public void send(@RequestBody MessageDO message) {
        distributor.distribute("sse:message:channel", JSONUtil.toJsonStr(message));
    }
}
